<template>
  <div class="box">
    <p class="p_title">
      <el-button type="text" style="color: #000;font-size: 16px">组织单位列表</el-button>
    </p>
    <div>
      <span style="font-size: 14px;margin-right: 10px">单位筛选</span>
      <el-cascader
        :options="unitData"
        v-model="unitIndexData"
        style="width: 20%"
        clearable
        filterable
        @change="handleChange(unitIndexData)">
      </el-cascader>

      <el-select v-model="detailType" placeholder="请选择并联部门" style="width: 18%;margin-left: 30px" clearable v-if="blbmSelectShow" @change="blbmSelectEvent(detailType)">
        <el-option
          v-for="item in blbmOptions"
          :key="item.id"
          :label="item.name"
          :value="item.id">
        </el-option>
      </el-select>
      <el-input placeholder="请输入内容" v-model="fuzzySearch" style="width: 20%;margin-left: 30px">
        <el-button slot="append" icon="el-icon-search" @click="searchvalEvent(fuzzySearch)"></el-button>
      </el-input>
      <el-button @click="czEvent">重置</el-button>
      <el-button type="primary" style="float: right;margin-left: 20px;" @click="addUnitEvent"> + 添加组织单位</el-button>
      <el-button type="primary" style="float: right" @click="addPermissions"> + 批量添加单位权限</el-button>
    </div>

    <!--  弹框 -->
    <el-dialog :title="(bjOrck)+'组织单位'" :visible.sync="addUnit" width="35%"
               :before-close="handleDepartmentClose" :modal-append-to-body="false">
      <el-form :model="addUnitForm" :rules="rules" ref="addUnitForm" label-width="130px">
        <el-form-item label="组织类型" prop="orgtypeid">
          <el-cascader
            :options="tancData"
            v-model="zzlxData"
            style="width: 100%"
            clearable
            @change="handleChangeTanc(zzlxData)" v-if="!ljShow">
          </el-cascader>
          <el-input v-model="lj" @focus="inpChange" v-if="ljShow"></el-input>
        </el-form-item>
        <el-form-item label="选择区域" prop="areas" v-if="gwhShow">
          <el-select v-model="addUnitForm.areas" style="width: 100%;" placeholder="请选择区域" filterable multiple>
            <el-option v-for="item in xzqyOptions" :key="item.regionid" :label="item.name"
                       :value="item.regionid"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="并联部门" prop="type" v-if="blbmShow">
          <el-select v-model="addUnitForm.type" style="width: 100%;" placeholder="请选择并联部门的分类" filterable>
            <el-option v-for="item in blbmOptions" :key="item.id" :label="item.name"
                       :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="组织机构名称" prop="orgname">
          <el-input v-model="addUnitForm.orgname"></el-input>
        </el-form-item>
        <el-form-item label="组织机构代码" prop="orgcode">
          <el-input v-model="addUnitForm.orgcode"></el-input>
        </el-form-item>
        <el-form-item label="单位简称" prop="orgsname">
          <el-input v-model="addUnitForm.orgsname"></el-input>
        </el-form-item>
        <el-form-item label="单位代码" prop="dwcode">
          <el-input v-model="addUnitForm.dwcode"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="addUnitForm.description"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitAddUnit">确 定</el-button>
        </span>
    </el-dialog>

    <el-table
      :data="tableData"
      border
      v-loading="loading"
      style="width: 100%;margin-top: 20px" @selection-change="handleSelectionChange">
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column
        align='center'
        prop="index"
        label="序号"
        width="80">
      </el-table-column>
      <el-table-column
        align='center'
        prop="orgname"
        label="组织单位名称">
      </el-table-column>
      <el-table-column
        align='center'
        prop="orgcode"
        label="组织机构代码/统一社会信用代码">
      </el-table-column>
      <el-table-column
        align='center'
        prop="bmType"
        label="部门类型">
      </el-table-column>
      <el-table-column
        align='center'
        prop="address"
        label="操作">
        <template slot-scope="scope">
          <el-button size="small" @click="seeEvent(1,1,scope.row)">查看</el-button>
          <el-button size="small" @click="seeEvent(2,1,scope.row)">编辑</el-button>
          <el-button size="small" @click="seeEvent(3,1,scope.row)">添加管理员</el-button>
          <el-button size="small" @click="seeEvent(4,1,scope.row)">添加权限</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="提示" :visible.sync="AdoptVisbile" width="30%" center :modal-append-to-body="false">
      <span>确定批量添加单位权限吗？</span>
      <span slot="footer" class="dialog-footer">
          <el-button @click="AdoptVisbile = false">取 消</el-button>
          <el-button type="primary" @click="Adopt">确 定</el-button>
        </span>
    </el-dialog>

    <div style="width: 100%;margin: 20px 0;height: 40px;line-height: 40px">
      <div style="float: right">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                       :current-page="currentPage4" :page-sizes="[10, 20, 30, 40, 50]" :page-size="10"
                       layout="total, sizes, prev, pager, next, jumper" :total=total></el-pagination>
      </div>
    </div>
  </div>
</template>

<script>

  import {$aos} from "../../../store/state";
  import {http} from "../../../assets/commonjs/axios";
  import {Copy, delSurplus} from "../../../assets/commonjs/utils";

  export default {
    data() {
      return {
        obj:{},
        detailType:'',
        blbmSelectShow:false,
        blbmOptions:[],//并联部门数据
        AdoptVisbile: false,
        multipleSelection: [],
        ljShow: false,
        lj: '',
        fuzzySearch: '',
        bjOrck: '',
        orgId: '',
        unitData: [],
        tancData: [],
        unitIndexData: [],
        tableData: [],
        pages: '',//每页条数
        pgindex: '',//当前页
        loading: true,
        currentPage4: 1,
        total: 0,
        bmList:[],
        originList:[],
        // ================= 添加组织单位  =================
        addUnit: false,
        zzlxOptions: [],
        xzqyOptions: [],
        blbmOptions: [],
        zzlxData: [],
        gwhShow: false,
        blbmShow: false,
        addUnitForm: {
          applytype: '',//1 新增 2 编辑 3 注销 4 查看
          orgtypeid: '',//组织类型
          areas: [],//选择区域
          type: '',//并联部门
          orgname: "",//组织机构名称
          orgsname: "",//单位简称,
          orgcode: "",//组织机构代码
          dwcode:'',//单位代码
          description: "",//描述
        },
        rules: {
          orgtypeid: [
            {required: true, message: "请选择组织类型", trigger: "blur"}
          ],
          type: [
            {required: true, message: "请选择组织类型", trigger: "blur"}
          ],
          orgname: [
            {required: true, message: "请选择并联部门", trigger: "blur"}
          ],
          // orgsname: [
          //   {required: true, message: "请输入单位简称", trigger: "blur"}
          // ],
          // orgcode: [
          //   {required: true, message: "请输入组织机构代码", trigger: "blur"}
          // ],
        },
        // ================================================
      }
    },
    created() {
      $aos.getItem('loginData').then(res => {
        this.orgId = res.org.orgid;
        this.OrganizationEvent()
        this.unitEvent({})
      });
      this.getAllArea();
      this.blbmEvent();
    },
    methods: {
      blbmSelectEvent(val){
        this.unitEvent({
          isCity: this.obj.isCity || '',
          area: this.obj.area || '',
          type: this.obj.type || '',
          detailType:val || '',
          cityAreaType: this.obj.cityAreaType || '',
          pageIndex: this.pgindex,
          pageNum: this.pages,
          fuzzySearch: this.fuzzySearch || ''
        })
      },


      Adopt() {
        this.AdoptVisbile = false;
        let orgIds = [];
        for (let i = 0; i < this.multipleSelection.length; i++) {
          orgIds.push(parseFloat(this.multipleSelection[i].orgIds));
        }
        $aos.setItem('orgIdList', orgIds.toString());
        $aos.setItem('tabNum', 4);
        this.$router.push({path: '/containerDetail', query: {index: 1}})
      },
      addPermissions() {
        if (this.multipleSelection === undefined || this.multipleSelection.length === 0) {
          this.$message({type: 'warning', message: '请选择单位后操作！'});
        } else {
          this.AdoptVisbile = true;
        }
      },
      handleSelectionChange(val) {
        this.multipleSelection = [];
        val.forEach(item => {
          this.multipleSelection.push({
            orgIds: item.orgid
          })
        })
      },
      //查询所有的区
      getAllArea() {
        http('post', 'permission/list_area').then(res => {
          if (res.data.success) {
            this.xzqyOptions = res.data.data;
          }
        })
      },
      //获取并联部门数据
      blbmEvent() {
        http('post', 'permission/list_unit_type').then(res => {
          if (res.data.success) {
            this.blbmOptions = res.data.data;
          }
        })
      },

      //添加组织单位
      addUnitEvent() {
        this.bjOrck = "添加"
        this.zzlxData = [];
        this.addUnit = true;
        this.addUnitForm = {
          applytype: '',//1 新增 2 编辑 3 注销 4 查看
          orgtypeid: '',//组织类型
          areas: [],//选择区域
          type: '',//并联部门
          orgname: "",//组织机构名称
          orgsname: "",//单位简称,
          orgcode: "",//组织机构代码
          dwcode:'',//单位代码
          description: "",//描述
        },
          this.addUnitForm.applytype = 1;

      },

      handleChangeTanc(val) {
        if (val.length) {
          let object = val[val.length - 1]
          this.addUnitForm.orgtypeid = object.cityAreaType;
          if (object.type === '03') {
            this.blbmShow = true
            this.gwhShow = false
          } else if (object.type === '99' && object.isCity === 1) {
            this.blbmShow = false
            this.gwhShow = true
          } else {
            this.blbmShow = false
            this.gwhShow = false
          }
        }
      },

      //离开提示
      handleDepartmentClose(done) {
        this.$refs.addUnitForm.resetFields();
        done()
      },
      //弹窗确定按钮
      submitAddUnit() {
        this.$refs.addUnitForm.validate((valid) => {
          if (valid) {
            Copy(this.addUnitForm, "submitdata");
            submitdata.areas = this.addUnitForm.areas.toString();
            this.zzdwAip(submitdata)
          }
        });
      },

      //组织单位接口
      zzdwAip(obj) {
        http('post', 'permission/opera_org', {
          org: obj ? obj : this.addUnitForm
        }).then(res => {
          if (res.data.success) {
            this.addUnit = false;
            this.unitEvent({
              isCity: this.obj.isCity || '',
              area: this.obj.area || '',
              type: this.obj.type || '',
              cityAreaType: this.obj.cityAreaType || '',
              pageIndex: this.pgindex,
              pageNum: this.pages,
            })
            this.detailType = '';
            this.$message({message: res.data.msg, type: 'success'});
          } else {
            this.$message({message: res.data.msg, type: 'warning'});
          }
        })
      },
      OrganizationEvent() {//组织机构事件
        http('post', 'permission/list_org_type', {
          "isCity": "",
          "area": "",
          "type": "",
          "cityAreaType": ""
        }).then(res => {
          let data = res.data.data;
          $aos.setItem('typeData', data)
          this.bmList = data;
          this.unitData = this.getJsonTree(data);
          this.tancData = this.getJsonTreetc(data);
        })
      },
      //把得到的数据变成需要的树结构
      getJsonTree(data) {
        if (data.length) {
          let itemArr = [];//总的数组，
          let sjObj = {children: [], label: "市级", value: 1};//市级对象，
          let qjObj = {children: [], label: "区级", value: 2};//区级对象，
          let qjData = [];
          let qjAreaSx = [];
          data.forEach(item => {
            if (item.isCity === 1) {
              let newArea = {};
              newArea.value = {};
              newArea.value.isCity = item.isCity;
              newArea.value.type = item.type;
              newArea.value.cityAreaType = item.cityAreaType;
              newArea.label = item.typeName;
              sjObj.children.push(newArea)
            } else if (item.isCity === 2) {
              qjData.push(item)
              if (qjAreaSx.indexOf(item.area) === -1) {
                qjAreaSx.push(item.area)
              }
            }
          });
          //区级结构遍历生成
          for (let i = 0; i < qjAreaSx.length; i++) {
            let newArea = {};
            newArea.value = {};
            qjData.forEach(item => {
              if (qjAreaSx[i] == item.area) {
                newArea.value.isCity = item.isCity;
                newArea.value.area = item.area;
                newArea.areas = item.area;
                newArea.label = item.areaName;
                newArea.children = [];
              }
            })
            qjObj.children.push(newArea)
          }
          //区级子级遍历生成
          let qjzjData = qjObj.children
          for (let arIndex in qjzjData) {
            let nodeA = qjzjData[arIndex];
            let step = 0;
            for (let s = 0; s < qjData.length; s++) {
              if (qjData[s].area == nodeA.areas) {
                step++;
                if (step === 1) {//给每一个区级下面添加全部
                  let nodesd = qjData[s];
                  let newArea = {};
                  newArea.value = {};
                  newArea.value.isCity = nodesd.isCity;
                  newArea.value.area = nodesd.area;
                  newArea.label = '全部';
                  qjObj.children[arIndex].children.unshift(newArea)
                }
                let nodes = qjData[s];
                let newArea = {};
                newArea.value = {};
                newArea.value.isCity = nodes.isCity;
                newArea.value.area = nodes.area;
                newArea.value.type = nodes.type;
                newArea.value.cityAreaType = nodes.cityAreaType;
                newArea.label = nodes.typeName;
                qjObj.children[arIndex].children.push(newArea)
              }
            }
          }
          //市级添加全部
          let sjQb = {};
          sjQb.value = {};
          sjQb.value.isCity = 1;
          sjQb.label = '全部';
          sjObj.children.unshift(sjQb)
          //区级添加全部
          let qjQb = {};
          qjQb.value = {};
          qjQb.value.isCity = 2;
          qjQb.label = '全部';
          qjObj.children.unshift(qjQb)
          itemArr.push(sjObj)
          itemArr.push(qjObj)
          return itemArr;
        }
      },

      //把得到的数据变成需要的树结构(弹出窗里的没有全部)
      getJsonTreetc(data) {
        if (data.length) {
          let itemArr = [];//总的数组，
          let sjObj = {children: [], label: "市级", value: 1};//市级对象，
          let qjObj = {children: [], label: "区级", value: 2};//区级对象，
          let qjData = [];
          let qjAreaSx = [];
          data.forEach(item => {
            if (item.isCity === 1) {
              let newArea = {};
              newArea.value = {};
              newArea.value.isCity = item.isCity;
              newArea.value.type = item.type;
              newArea.value.cityAreaType = item.cityAreaType;
              newArea.label = item.typeName;
              sjObj.children.push(newArea)
            } else if (item.isCity === 2) {
              qjData.push(item)
              if (qjAreaSx.indexOf(item.area) === -1) {
                qjAreaSx.push(item.area)
              }
            }
          });
          //区级结构遍历生成
          for (let i = 0; i < qjAreaSx.length; i++) {
            let newArea = {};
            newArea.value = {};
            qjData.forEach(item => {
              if (qjAreaSx[i] == item.area) {
                newArea.value.isCity = item.isCity;
                newArea.value.area = item.area;
                newArea.areas = item.area;
                newArea.label = item.areaName;
                newArea.children = [];
              }
            })
            qjObj.children.push(newArea)
          }
          //区级子级遍历生成
          let qjzjData = qjObj.children
          for (let arIndex in qjzjData) {
            let nodeA = qjzjData[arIndex];
            for (let s = 0; s < qjData.length; s++) {
              if (qjData[s].area == nodeA.areas) {
                let nodes = qjData[s];
                let newArea = {};
                newArea.value = {};
                newArea.value.isCity = nodes.isCity;
                newArea.value.area = nodes.area;
                newArea.value.type = nodes.type;
                newArea.value.cityAreaType = nodes.cityAreaType;
                newArea.label = nodes.typeName;
                qjObj.children[arIndex].children.push(newArea)
              }
            }
          }
          itemArr.push(sjObj)
          itemArr.push(qjObj)
          return itemArr;
        }
      },
      handleChange(val) {
        if (val.length) {
          this.obj =  val[val.length - 1]
          this.unitEvent({
            isCity: this.obj.isCity || '',
            area: this.obj.area || '',
            type: this.obj.type || '',
            cityAreaType: this.obj.cityAreaType || '',
            pageIndex: this.pgindex,
            pageNum: this.pages,
            fuzzySearch: this.fuzzySearch || ''
          })
          if(this.obj.type === '03'){
            this.blbmSelectShow = true;
          }else{
            this.blbmSelectShow = false;
          }
        } else {
          this.blbmSelectShow = false;
          this.obj = {};
          this.unitEvent({});
        }
      },
      //获取相应的单位
      unitEvent(val) {
        const params = {
          isCity: val.isCity || '',
          area: val.area || '',
          type: val.type || '',
          detailType:val.detailType || '',
          cityAreaType: val.cityAreaType || '',
          pageIndex: val.pageIndex || this.pgindex || 1,
          pageNum: val.pages || this.pages || 10,
          fuzzySearch: this.fuzzySearch || ''
        }
        http('post', 'permission/list_org', params).then(res => {
          if (res.data.success) {
            let data = res.data.data;
            let projects = data.list || [];
            //保留this
            var _this = this
            projects.forEach(function (item, index) {
              //分页
              if (_this.pages == 0) {
                if (val.pageIndex > 1) {
                  item.index = (val.pageIndex - 1) * 10 + index + 1;
                } else {
                  item.index = index + 1
                }
              } else if (_this.pages != 0) {
                if (val.pageIndex > 1) {
                  item.index = (val.pageIndex - 1) * _this.pages + index + 1;
                } else {
                  item.index = index + 1
                }
              }
            })
            this.tableData = projects;
            this.loading = false;
            this.total = data.total;
            this.tableData.forEach((item,index)=>{
              this.bmList.forEach(tem=>{
                if(item.orgtypeid === tem.cityAreaType){
                  if(item.type){
                    this.blbmOptions.forEach(bmitem=>{
                      if(item.type === bmitem.id){
                        this.tableData[index].bmType = bmitem.name;
                      }
                    })
                  }else{
                    this.tableData[index].bmType = tem.typeName
                  }
                }
              })
            })
          }
        })
      },
      czEvent(){
        this.unitIndexData = [];
        this.obj = {};
        this.fuzzySearch = '';
        this.detailType = '';
        this.unitEvent({});
      },

      searchvalEvent(val) {
        this.unitEvent({
          isCity: this.obj.isCity || '',
          area: this.obj.area || '',
          type: this.obj.type || '',
          detailType: this.detailType || '',
          cityAreaType: this.obj.cityAreaType || '',
          pageIndex:this.pgindex || '',
          pageNum:this.pages || '',
          fuzzySearch: val,
        });
      },


      //改变每页条数事件
      handleSizeChange(val) {
        this.pages = val
        this.unitEvent({
          isCity: this.obj.isCity || '',
          area: this.obj.area || '',
          type: this.obj.type || '',
          detailType: this.detailType || '',
          cityAreaType: this.obj.cityAreaType || '',
          pageIndex:this.pgindex || '',
          pageNum:this.pages || '',
          fuzzySearch: this.fuzzySearch,
        })
      },
      //改变当前是第几页
      handleCurrentChange(val) {
        this.pgindex = val
        this.unitEvent({
          isCity: this.obj.isCity || '',
          area: this.obj.area || '',
          type: this.obj.type || '',
          detailType: this.detailType || '',
          cityAreaType: this.obj.cityAreaType || '',
          pageIndex:this.pgindex || '',
          pageNum:this.pages || '',
          fuzzySearch: this.fuzzySearch,
        })
      },

      //key是标识是编辑还是查看还是..等等，index是标识是侧边栏的第几个
      //index: 1(添加单位)，2（模板设置），3（审计信息）4（个人信息）
      //row
      seeEvent(key, index, row) {
       if(row.areas === null){ row.areas = []}
        $aos.setItem('orgIdList', row.orgid.toString());
        $aos.setItem('permissions', row);
        if (key === 2) {
          this.zzlxData = [];
          let lx = row.orgtypeid.slice(row.orgtypeid.length - 2, row.orgtypeid.length);
          if (lx === '03') {
            this.blbmShow = true
            this.gwhShow = false
          } else if (lx === '99') {
            this.blbmShow = false
            this.gwhShow = true
          } else {
            this.blbmShow = false
            this.gwhShow = false
          }
          this.bjOrck = "编辑";
          this.ljShow = true;
          this.addUnit = true;
          this.addUnitForm = delSurplus(row, this.addUnitForm);
          this.addUnitForm.applytype = 2;
          this.addUnitForm.orgid = row.orgid;
          let obj = {
            applyType: 4,
            orgId: row.orgid,
          };
          http('post', 'permission/opera_org', {
            org: obj
          }).then(res => {
            if (res.data.success) {
              let data1 = res.data.data.org;
              if (data1.areas) {
                this.addUnitForm.areas = data1.areas.split(',');
              }else {
                this.addUnitForm.areas = [];
              }
              let data = res.data.data.orgType;
              if (data.isCity === 1) {
                this.lj = '市级/' + data.typeName
              } else if (data.isCity === 2) {
                this.lj = '区级/' + data.areaName + '/' + data.typeName
              }

            }
          })
        } else {
          $aos.setItem('tabNum', key)
          $aos.setItem('unitData', row)
          this.$router.push({path: '/containerDetail', query: {index: index, orgId: row.orgid}})
        }
      },

      inpChange() {
        this.ljShow = false;
      }

    }

  }

</script>

<style scoped>
  .box {
    background: #fff;
    padding: 0 30px 30px 30px;
  }

  .p_title {
    padding: 0;
    margin: 0 0 10px 0;
  }
</style>
